from flask import render_template, redirect, url_for, flash, request, abort
from app.forms import *
from app.models import User, Blog, Friend
from flask_login import login_user, logout_user, current_user
from . import user


@user.route("/register", methods=["GET", "POST"])
def register():
    """注册页面"""
    form = UserRegisterForm()
    # 校验用户的输入
    if form.validate_on_submit():
        # 注册
        form.register(form.data)
        # 返回到登录页面
        flash({"success": "注册成功！请登录！"})
        return redirect(url_for("user.login"))
    else:
        print(form.errors)
        flash(form.errors)
    return render_template("/user/register.html", form=form)


@user.route("/login", methods=["GET", "POST"])
def login():
    """登录页面"""
    form = UserLoginForm()
    next_url = request.args.get("next")
    # 校验用户的输入
    if form.validate_on_submit():
        account = form.data.get("account")
        password = form.data.get("password")
        remember_me = form.data.get("remember_me")
        user = User.getUserByAccount(account)
        if user and user.validate_password(password):
            login_user(user, remember=remember_me)
            # 判断next_url是否为空
            if next_url:
                return redirect(next_url)

            flash({"success": "登录成功！ {0}, 欢迎回来！".format(user.username)})
            return redirect(url_for("home.index"))
        else:
            flash({"error": "用户名或密码错误！"})
    else:
        flash(form.errors)
    return render_template("/user/login.html", form=form, next_url=next_url)

@user.route("/logout")
def logout():
    """退出登录"""
    logout_user()
    return redirect(url_for("home.index"))

@user.route("/<int:id>")
def index(id):
    """个人简介"""
    user = User.getUserById(user_id=id)
    # 如果用户不存在报404错误
    if not user:
        abort(404)
    blogs = Blog.getList(user_id=id)
    friend = {}
    if current_user and current_user.get_id():
        print("-ok-")
        friend = Friend.getByFromUserId(from_user_id=current_user.id)
    print(friend)
    return render_template("user/profile.html", blogs=blogs, user=user, friend=friend)